<template>
  <div class="api-designer-page">
    <div class="page-header">
      <h2>API接口设计器</h2>
      <div class="header-actions">
        <el-button @click="showAIDialog = true" type="primary">
          <el-icon><MagicStick /></el-icon>
          AI生成
        </el-button>
        <el-button type="success" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新建接口
        </el-button>
      </div>
    </div>

    <div class="designer-layout">
      <!-- 左侧：分类树 -->
      <div class="category-panel">
        <el-card class="category-card">
          <template #header>
            <div class="panel-header">
              <span>接口分类</span>
              <el-button size="small" text @click="handleAddCategory">
                <el-icon><Plus /></el-icon>
              </el-button>
            </div>
          </template>

          <div class="category-content">
            <el-input
              v-model="categorySearch"
              placeholder="搜索分类..."
              size="small"
              clearable
              style="margin-bottom: 10px"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>

            <el-tree
              ref="categoryTreeRef"
              :data="categoryTree"
              :props="{ label: 'name', children: 'children' }"
              :filter-node-method="filterCategoryNode"
              :highlight-current="true"
              node-key="id"
              default-expand-all
              @node-click="handleCategoryClick"
            >
              <template #default="{ node, data }">
                <div class="tree-node">
                  <span class="node-label">
                    <el-icon><Folder /></el-icon>
                    <span>{{ data.name }}</span>
                    <el-badge :value="data.count" :max="99" class="count-badge" />
                  </span>
                  <span class="node-actions" @click.stop>
                    <el-button size="small" text @click="handleEditCategory(data)">
                      <el-icon><Edit /></el-icon>
                    </el-button>
                    <el-button size="small" text type="danger" @click="handleDeleteCategory(data)">
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </span>
                </div>
              </template>
            </el-tree>
          </div>
        </el-card>
      </div>

      <!-- 中间：接口列表 -->
      <div class="api-list-panel">
        <el-card class="api-card">
          <template #header>
            <div class="panel-header">
              <span>{{ currentCategory ? currentCategory.name : '全部接口' }}</span>
            </div>
          </template>

          <!-- 搜索区域 -->
          <el-form :inline="true" class="search-form">
            <el-form-item label="接口名称">
              <el-input v-model="searchForm.name" placeholder="请输入接口名称" clearable size="small" />
            </el-form-item>
            <el-form-item label="请求方法">
              <el-select v-model="searchForm.method" placeholder="请选择" clearable size="small">
                <el-option label="GET" value="GET" />
                <el-option label="POST" value="POST" />
                <el-option label="PUT" value="PUT" />
                <el-option label="DELETE" value="DELETE" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch" size="small">查询</el-button>
              <el-button @click="handleReset" size="small">重置</el-button>
            </el-form-item>
          </el-form>

          <!-- 接口列表 -->
          <div class="api-list">
            <div
              v-for="api in filteredApis"
              :key="api.id"
              class="api-item"
              :class="{ active: selectedAPI?.id === api.id }"
              @click="handleSelectAPI(api)"
            >
              <div class="api-item-header">
                <el-tag :type="getMethodType(api.method)" size="small">{{ api.method }}</el-tag>
                <span class="api-name">{{ api.name }}</span>
                <el-tag v-if="api.status === 1" type="success" size="small">已发布</el-tag>
                <el-tag v-else type="warning" size="small">草稿</el-tag>
              </div>
              <div class="api-path">{{ api.path }}</div>
              <div class="api-description">{{ api.description }}</div>
              <div class="api-footer">
                <span class="api-time">{{ api.createTime }}</span>
                <div class="api-actions">
                  <el-button size="small" text type="primary" @click.stop="handleEdit(api)">
                    <el-icon><Edit /></el-icon>
                  </el-button>
                  <el-button size="small" text type="success" @click.stop="handleTest(api)">
                    <el-icon><VideoPlay /></el-icon>
                  </el-button>
                  <el-button size="small" text type="info" @click.stop="handleViewDoc(api)">
                    <el-icon><Document /></el-icon>
                  </el-button>
                  <el-button size="small" text type="danger" @click.stop="handleDelete(api)">
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </div>
            </div>
          </div>

          <el-empty v-if="!filteredApis.length" description="暂无接口" />
        </el-card>
      </div>
    </div>

    <!-- 分类管理对话框 -->
    <el-dialog
      v-model="categoryDialogVisible"
      :title="categoryDialogTitle"
      width="500px"
    >
      <el-form :model="categoryForm" label-width="80px">
        <el-form-item label="分类名称">
          <el-input v-model="categoryForm.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="父级分类">
          <el-tree-select
            v-model="categoryForm.parentId"
            :data="categoryTreeOptions"
            :props="{ label: 'name', children: 'children' }"
            placeholder="请选择父级分类（可选）"
            clearable
            check-strictly
          />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="categoryForm.sort" :min="0" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="categoryForm.description" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="categoryDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveCategory">保存</el-button>
      </template>
    </el-dialog>

    <!-- 编辑接口对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="1200px"
      :close-on-click-modal="false"
      fullscreen
    >
      <div class="api-editor">
        <el-row :gutter="20">
          <!-- 左侧：接口配置 -->
          <el-col :span="10">
            <el-card shadow="never" class="config-card">
              <template #header>
                <span>接口配置</span>
              </template>
              <el-form :model="form" label-width="100px" size="small">
                <el-form-item label="接口名称">
                  <el-input v-model="form.name" placeholder="如：获取用户列表" />
                </el-form-item>
                
                <el-form-item label="所属分类">
                  <el-tree-select
                    v-model="form.categoryId"
                    :data="categoryTreeOptions"
                    :props="{ label: 'name', children: 'children' }"
                    placeholder="请选择分类"
                    clearable
                    check-strictly
                  />
                </el-form-item>
                
                <el-form-item label="接口路径">
                  <el-input v-model="form.path" placeholder="如：/api/users">
                    <template #prepend>
                      <el-select v-model="form.method" style="width: 100px">
                        <el-option label="GET" value="GET" />
                        <el-option label="POST" value="POST" />
                        <el-option label="PUT" value="PUT" />
                        <el-option label="DELETE" value="DELETE" />
                      </el-select>
                    </template>
                  </el-input>
                </el-form-item>

                <el-form-item label="描述">
                  <el-input v-model="form.description" type="textarea" :rows="2" />
                </el-form-item>

                <el-divider content-position="left">数据库配置</el-divider>

                <el-form-item label="数据源">
                  <el-select v-model="form.datasource" placeholder="选择数据源">
                    <el-option label="主数据库" value="main" />
                    <el-option label="只读数据库" value="readonly" />
                  </el-select>
                </el-form-item>

                <el-form-item label="查询类型">
                  <el-radio-group v-model="form.queryType">
                    <el-radio value="select">查询</el-radio>
                    <el-radio value="insert">新增</el-radio>
                    <el-radio value="update">更新</el-radio>
                    <el-radio value="delete">删除</el-radio>
                  </el-radio-group>
                </el-form-item>

                <el-divider content-position="left">请求参数</el-divider>

                <div class="params-config">
                  <el-button size="small" @click="addParam">
                    <el-icon><Plus /></el-icon>
                    添加参数
                  </el-button>

                  <div v-for="(param, index) in form.params" :key="index" class="param-item">
                    <el-input v-model="param.name" placeholder="参数名" size="small" style="width: 120px" />
                    <el-select v-model="param.type" placeholder="类型" size="small" style="width: 100px">
                      <el-option label="字符串" value="string" />
                      <el-option label="数字" value="number" />
                      <el-option label="布尔" value="boolean" />
                      <el-option label="数组" value="array" />
                    </el-select>
                    <el-checkbox v-model="param.required" size="small">必填</el-checkbox>
                    <el-input v-model="param.description" placeholder="说明" size="small" style="width: 150px" />
                    <el-button size="small" type="danger" link @click="removeParam(index)">删除</el-button>
                  </div>
                </div>

                <el-divider content-position="left">响应配置</el-divider>

                <el-form-item label="分页">
                  <el-switch v-model="form.pagination" />
                  <span class="form-tip">开启后自动添加分页参数</span>
                </el-form-item>

                <el-form-item label="缓存">
                  <el-switch v-model="form.cache" />
                  <el-input-number 
                    v-if="form.cache" 
                    v-model="form.cacheTime" 
                    :min="1" 
                    size="small"
                    style="margin-left: 10px"
                  />
                  <span v-if="form.cache" class="form-tip">秒</span>
                </el-form-item>
              </el-form>
            </el-card>
          </el-col>

          <!-- 右侧：SQL编辑器 -->
          <el-col :span="14">
            <el-card shadow="never" class="sql-card">
              <template #header>
                <div class="sql-header">
                  <span>SQL语句</span>
                  <el-button-group size="small">
                    <el-button @click="showTables = !showTables">
                      <el-icon><Grid /></el-icon>
                      {{ showTables ? '隐藏' : '显示' }}表结构
                    </el-button>
                  </el-button-group>
                </div>
              </template>

              <div class="sql-content">
                <!-- 表结构面板 -->
                <el-drawer
                  v-model="showTables"
                  title="数据表结构"
                  direction="rtl"
                  size="400px"
                  :append-to-body="true"
                >
                  <div class="tables-list">
                    <el-input
                      v-model="tableSearch"
                      placeholder="搜索表..."
                      size="small"
                      style="margin-bottom: 10px"
                    >
                      <template #prefix>
                        <el-icon><Search /></el-icon>
                      </template>
                    </el-input>

                    <el-collapse v-model="activeTable">
                      <el-collapse-item
                        v-for="table in filteredTables"
                        :key="table.name"
                        :name="table.name"
                      >
                        <template #title>
                          <el-icon><Grid /></el-icon>
                          <span style="margin-left: 10px">{{ table.name }}</span>
                        </template>
                        <div class="table-fields">
                          <div v-for="field in table.fields" :key="field.name" class="field-item">
                            <el-icon><Coin /></el-icon>
                            <span class="field-name">{{ field.name }}</span>
                            <span class="field-type">{{ field.type }}</span>
                            <span class="field-comment">{{ field.comment }}</span>
                          </div>
                        </div>
                      </el-collapse-item>
                    </el-collapse>
                  </div>
                </el-drawer>

                <!-- SQL编辑器 -->
                <SQLEditor
                  v-model="form.sql"
                  :tables="databaseTables"
                  @execute="handleExecuteSQL"
                />

                <!-- SQL参数绑定提示 -->
                <el-alert
                  title="参数绑定说明"
                  type="info"
                  :closable="false"
                  style="margin-top: 10px"
                >
                  <template #default>
                    <div>在SQL中使用 <code>#{paramName}</code> 来绑定请求参数</div>
                    <div>示例：<code>WHERE id = #{id}</code></div>
                  </template>
                </el-alert>

                <!-- SQL执行结果 -->
                <div v-if="sqlResult" class="sql-result">
                  <el-divider content-position="left">执行结果</el-divider>
                  <el-table :data="sqlResult.data" border size="small" max-height="300">
                    <el-table-column
                      v-for="col in sqlResult.columns"
                      :key="col"
                      :prop="col"
                      :label="col"
                      min-width="120"
                    />
                  </el-table>
                  <div class="result-info">
                    <span>查询时间: {{ sqlResult.time }}ms</span>
                    <span>返回行数: {{ sqlResult.data.length }}</span>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button @click="handleSaveDraft">保存草稿</el-button>
        <el-button type="primary" @click="handleSubmit">发布接口</el-button>
      </template>
    </el-dialog>

    <!-- AI生成对话框 -->
    <el-dialog v-model="showAIDialog" title="AI生成接口" width="700px">
      <el-alert
        title="描述你想要的接口功能，AI会自动生成完整的接口配置和SQL"
        type="info"
        :closable="false"
        style="margin-bottom: 20px"
      />
      <el-input
        v-model="aiPrompt"
        type="textarea"
        :rows="5"
        placeholder="例如：创建一个查询用户列表的接口，支持按用户名搜索和分页"
      />
      <template #footer>
        <el-button @click="showAIDialog = false">取消</el-button>
        <el-button type="primary" @click="handleAIGenerate" :loading="aiGenerating">
          生成接口
        </el-button>
      </template>
    </el-dialog>

    <!-- 接口测试对话框 -->
    <el-dialog v-model="showTestDialog" title="接口测试" width="900px">
      <div class="test-container">
        <el-form label-width="100px">
          <el-form-item label="请求地址">
            <el-input :value="testAPI?.fullPath" disabled>
              <template #prepend>
                <el-tag :type="getMethodType(testAPI?.method)">{{ testAPI?.method }}</el-tag>
              </template>
            </el-input>
          </el-form-item>

          <el-divider content-position="left">请求参数</el-divider>

          <div v-for="param in testAPI?.params" :key="param.name" class="test-param">
            <el-form-item :label="param.name">
              <el-input v-model="testParams[param.name]" :placeholder="param.description">
                <template #append>
                  <span>{{ param.type }}</span>
                </template>
              </el-input>
            </el-form-item>
          </div>

          <el-form-item>
            <el-button type="primary" @click="sendTestRequest" :loading="testing">
              发送请求
            </el-button>
          </el-form-item>
        </el-form>

        <el-divider content-position="left">响应结果</el-divider>

        <div v-if="testResponse" class="test-response">
          <div class="response-status" :class="{ success: testResponse.success }">
            <span>状态码: {{ testResponse.status }}</span>
            <span>耗时: {{ testResponse.time }}ms</span>
          </div>
          <pre class="response-body">{{ JSON.stringify(testResponse.data, null, 2) }}</pre>
        </div>
        <el-empty v-else description="发送请求后查看响应结果" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  MagicStick, Plus, Grid, Coin, Search, Folder, Edit, Delete, VideoPlay, Document
} from '@element-plus/icons-vue'
import SQLEditor from '@/components/common/SQLEditor.vue'

// 状态
const dialogVisible = ref(false)
const dialogTitle = ref('新建接口')
const showAIDialog = ref(false)
const showTestDialog = ref(false)
const showTables = ref(false)
const aiPrompt = ref('')
const aiGenerating = ref(false)
const tableSearch = ref('')
const activeTable = ref([])
const sqlResult = ref(null)
const testAPI = ref(null)
const testParams = reactive({})
const testResponse = ref(null)
const testing = ref(false)

// 分类相关状态
const categoryDialogVisible = ref(false)
const categoryDialogTitle = ref('新建分类')
const categorySearch = ref('')
const categoryTreeRef = ref(null)
const currentCategory = ref(null)
const selectedAPI = ref(null)

// 搜索表单
const searchForm = reactive({
  name: '',
  method: ''
})

// 分类表单
const categoryForm = reactive({
  id: null,
  name: '',
  parentId: null,
  sort: 0,
  description: ''
})

// 表单数据
const form = reactive({
  name: '',
  path: '',
  method: 'GET',
  description: '',
  categoryId: null,
  datasource: 'main',
  queryType: 'select',
  sql: '',
  params: [],
  pagination: false,
  cache: false,
  cacheTime: 60
})

// 分类树数据
const categoryTree = ref([
  {
    id: 1,
    name: '用户管理',
    count: 5,
    children: [
      { id: 11, name: '用户信息', count: 3 },
      { id: 12, name: '用户权限', count: 2 }
    ]
  },
  {
    id: 2,
    name: '商品管理',
    count: 8,
    children: [
      { id: 21, name: '商品信息', count: 4 },
      { id: 22, name: '库存管理', count: 3 },
      { id: 23, name: '价格管理', count: 1 }
    ]
  },
  {
    id: 3,
    name: '订单管理',
    count: 6,
    children: [
      { id: 31, name: '订单查询', count: 2 },
      { id: 32, name: '订单处理', count: 4 }
    ]
  },
  {
    id: 4,
    name: '系统管理',
    count: 4,
    children: [
      { id: 41, name: '配置管理', count: 2 },
      { id: 42, name: '日志管理', count: 2 }
    ]
  }
])

// 接口列表
const apis = ref([
  {
    id: 1,
    name: '获取用户列表',
    path: '/api/users',
    method: 'GET',
    description: '查询用户列表，支持分页和搜索',
    categoryId: 11,
    status: 1,
    createTime: '2025-01-15 10:00:00'
  },
  {
    id: 2,
    name: '创建用户',
    path: '/api/users',
    method: 'POST',
    description: '创建新用户',
    categoryId: 11,
    status: 1,
    createTime: '2025-01-15 11:30:00'
  },
  {
    id: 3,
    name: '更新用户信息',
    path: '/api/users/:id',
    method: 'PUT',
    description: '更新指定用户的信息',
    categoryId: 11,
    status: 1,
    createTime: '2025-01-15 12:00:00'
  },
  {
    id: 4,
    name: '获取用户权限',
    path: '/api/users/:id/permissions',
    method: 'GET',
    description: '获取用户的权限列表',
    categoryId: 12,
    status: 1,
    createTime: '2025-01-15 13:00:00'
  },
  {
    id: 5,
    name: '分配用户角色',
    path: '/api/users/:id/roles',
    method: 'POST',
    description: '为用户分配角色',
    categoryId: 12,
    status: 0,
    createTime: '2025-01-15 14:00:00'
  },
  {
    id: 6,
    name: '获取商品列表',
    path: '/api/products',
    method: 'GET',
    description: '查询商品列表',
    categoryId: 21,
    status: 1,
    createTime: '2025-01-16 10:00:00'
  },
  {
    id: 7,
    name: '获取商品详情',
    path: '/api/products/:id',
    method: 'GET',
    description: '获取商品详细信息',
    categoryId: 21,
    status: 1,
    createTime: '2025-01-16 11:00:00'
  },
  {
    id: 8,
    name: '创建商品',
    path: '/api/products',
    method: 'POST',
    description: '创建新商品',
    categoryId: 21,
    status: 1,
    createTime: '2025-01-16 12:00:00'
  },
  {
    id: 9,
    name: '更新库存',
    path: '/api/inventory/:id',
    method: 'PUT',
    description: '更新商品库存',
    categoryId: 22,
    status: 1,
    createTime: '2025-01-16 13:00:00'
  },
  {
    id: 10,
    name: '获取订单统计',
    path: '/api/orders/stats',
    method: 'GET',
    description: '获取订单统计数据',
    categoryId: 31,
    status: 0,
    createTime: '2025-01-16 14:20:00'
  }
])

// 数据库表结构
const databaseTables = ref([
  {
    name: 'sys_user',
    comment: '用户表',
    fields: [
      { name: 'id', type: 'INT', comment: '主键ID' },
      { name: 'username', type: 'VARCHAR(50)', comment: '用户名' },
      { name: 'password', type: 'VARCHAR(100)', comment: '密码' },
      { name: 'email', type: 'VARCHAR(100)', comment: '邮箱' },
      { name: 'phone', type: 'VARCHAR(20)', comment: '手机号' },
      { name: 'status', type: 'INT', comment: '状态' },
      { name: 'create_time', type: 'DATETIME', comment: '创建时间' }
    ]
  },
  {
    name: 'product',
    comment: '商品表',
    fields: [
      { name: 'id', type: 'INT', comment: '主键ID' },
      { name: 'name', type: 'VARCHAR(200)', comment: '商品名称' },
      { name: 'code', type: 'VARCHAR(50)', comment: '商品编码' },
      { name: 'price', type: 'DECIMAL(10,2)', comment: '价格' },
      { name: 'stock', type: 'INT', comment: '库存' },
      { name: 'status', type: 'INT', comment: '状态' }
    ]
  },
  {
    name: 'orders',
    comment: '订单表',
    fields: [
      { name: 'id', type: 'INT', comment: '主键ID' },
      { name: 'order_no', type: 'VARCHAR(50)', comment: '订单号' },
      { name: 'user_id', type: 'INT', comment: '用户ID' },
      { name: 'total_amount', type: 'DECIMAL(10,2)', comment: '总金额' },
      { name: 'status', type: 'INT', comment: '状态' },
      { name: 'create_time', type: 'DATETIME', comment: '创建时间' }
    ]
  }
])

// 过滤接口列表
const filteredApis = computed(() => {
  let result = apis.value
  
  // 按分类过滤
  if (currentCategory.value) {
    result = result.filter(api => {
      // 获取所有子分类ID
      const categoryIds = getAllChildCategoryIds(currentCategory.value.id)
      return categoryIds.includes(api.categoryId)
    })
  }
  
  // 按搜索条件过滤
  if (searchForm.name) {
    result = result.filter(api => 
      api.name.toLowerCase().includes(searchForm.name.toLowerCase()) ||
      api.path.toLowerCase().includes(searchForm.name.toLowerCase())
    )
  }
  
  if (searchForm.method) {
    result = result.filter(api => api.method === searchForm.method)
  }
  
  return result
})

// 分类树选项（用于下拉选择）
const categoryTreeOptions = computed(() => {
  return categoryTree.value
})

// 过滤表
const filteredTables = computed(() => {
  if (!tableSearch.value) return databaseTables.value
  return databaseTables.value.filter(t => 
    t.name.toLowerCase().includes(tableSearch.value.toLowerCase())
  )
})

// 获取所有子分类ID（包括自己）
const getAllChildCategoryIds = (categoryId) => {
  const ids = [categoryId]
  
  const findChildren = (categories) => {
    categories.forEach(cat => {
      if (cat.id === categoryId && cat.children) {
        cat.children.forEach(child => {
          ids.push(child.id)
          if (child.children) {
            ids.push(...getAllChildCategoryIds(child.id))
          }
        })
      } else if (cat.children) {
        findChildren(cat.children)
      }
    })
  }
  
  findChildren(categoryTree.value)
  return ids
}

// 监听分类搜索
watch(categorySearch, (val) => {
  categoryTreeRef.value?.filter(val)
})

// 方法类型标签
const getMethodType = (method) => {
  const typeMap = {
    GET: 'primary',
    POST: 'success',
    PUT: 'warning',
    DELETE: 'danger'
  }
  return typeMap[method] || ''
}

// 搜索
const handleSearch = () => {
  console.log('搜索:', searchForm)
  ElMessage.success('查询成功')
}

// 重置
const handleReset = () => {
  searchForm.name = ''
  searchForm.method = ''
  handleSearch()
}

// 选择接口
const handleSelectAPI = (api) => {
  selectedAPI.value = api
}

// 分类树过滤
const filterCategoryNode = (value, data) => {
  if (!value) return true
  return data.name.toLowerCase().includes(value.toLowerCase())
}

// 点击分类
const handleCategoryClick = (data) => {
  currentCategory.value = data
  selectedAPI.value = null
}

// 新增分类
const handleAddCategory = () => {
  categoryDialogTitle.value = '新建分类'
  Object.assign(categoryForm, {
    id: null,
    name: '',
    parentId: null,
    sort: 0,
    description: ''
  })
  categoryDialogVisible.value = true
}

// 编辑分类
const handleEditCategory = (data) => {
  categoryDialogTitle.value = '编辑分类'
  Object.assign(categoryForm, {
    id: data.id,
    name: data.name,
    parentId: data.parentId || null,
    sort: data.sort || 0,
    description: data.description || ''
  })
  categoryDialogVisible.value = true
}

// 删除分类
const handleDeleteCategory = (data) => {
  ElMessageBox.confirm(`确定要删除分类 "${data.name}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 这里应该调用API删除
    ElMessage.success('分类删除成功')
  })
}

// 保存分类
const handleSaveCategory = () => {
  if (!categoryForm.name) {
    ElMessage.warning('请输入分类名称')
    return
  }
  
  console.log('保存分类:', categoryForm)
  ElMessage.success(categoryForm.id ? '分类更新成功' : '分类创建成功')
  categoryDialogVisible.value = false
}

// 新增接口
const handleAdd = () => {
  dialogTitle.value = '新建接口'
  Object.assign(form, {
    name: '',
    path: '',
    method: 'GET',
    description: '',
    categoryId: currentCategory.value?.id || null,
    datasource: 'main',
    queryType: 'select',
    sql: '',
    params: [],
    pagination: false,
    cache: false,
    cacheTime: 60
  })
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑接口'
  Object.assign(form, {
    ...row,
    params: row.params || [],
    sql: row.sql || 'SELECT * FROM sys_user WHERE id = #{id}'
  })
  dialogVisible.value = true
}

// 添加参数
const addParam = () => {
  form.params.push({
    name: '',
    type: 'string',
    required: true,
    description: ''
  })
}

// 删除参数
const removeParam = (index) => {
  form.params.splice(index, 1)
}

// 执行SQL
const handleExecuteSQL = (sql) => {
  ElMessage.info('执行SQL...')
  
  // 模拟执行结果
  setTimeout(() => {
    sqlResult.value = {
      columns: ['id', 'username', 'email', 'status'],
      data: [
        { id: 1, username: 'admin', email: 'admin@example.com', status: 1 },
        { id: 2, username: 'user1', email: 'user1@example.com', status: 1 },
        { id: 3, username: 'user2', email: 'user2@example.com', status: 0 }
      ],
      time: 15
    }
    ElMessage.success('SQL执行成功')
  }, 500)
}

// 保存草稿
const handleSaveDraft = () => {
  console.log('保存草稿:', form)
  ElMessage.success('草稿保存成功')
}

// 提交
const handleSubmit = () => {
  if (!form.name || !form.path || !form.sql) {
    ElMessage.warning('请填写完整信息')
    return
  }
  
  console.log('发布接口:', form)
  ElMessage.success('接口发布成功')
  dialogVisible.value = false
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除接口 "${row.name}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
  })
}

// 测试接口
const handleTest = (row) => {
  testAPI.value = {
    ...row,
    fullPath: `http://localhost:3000${row.path}`,
    params: row.params || [
      { name: 'page', type: 'number', description: '页码' },
      { name: 'pageSize', type: 'number', description: '每页数量' }
    ]
  }
  showTestDialog.value = true
}

// 发送测试请求
const sendTestRequest = () => {
  testing.value = true
  
  setTimeout(() => {
    testResponse.value = {
      success: true,
      status: 200,
      time: 45,
      data: {
        code: 200,
        message: '成功',
        data: {
          total: 100,
          list: [
            { id: 1, name: '测试数据1' },
            { id: 2, name: '测试数据2' }
          ]
        }
      }
    }
    testing.value = false
    ElMessage.success('请求成功')
  }, 1000)
}

// 查看文档
const handleViewDoc = (row) => {
  ElMessage.info('文档功能开发中...')
}

// AI生成
const handleAIGenerate = () => {
  if (!aiPrompt.value.trim()) {
    ElMessage.warning('请输入需求描述')
    return
  }
  
  aiGenerating.value = true
  
  setTimeout(() => {
    Object.assign(form, {
      name: '获取用户列表',
      path: '/api/users',
      method: 'GET',
      description: 'AI生成的用户列表查询接口',
      datasource: 'main',
      queryType: 'select',
      sql: `SELECT 
  id,
  username,
  email,
  phone,
  status,
  create_time
FROM 
  sys_user
WHERE 
  username LIKE CONCAT('%', #{keyword}, '%')
  AND status = #{status}
ORDER BY 
  create_time DESC
LIMIT #{offset}, #{limit}`,
      params: [
        { name: 'keyword', type: 'string', required: false, description: '搜索关键词' },
        { name: 'status', type: 'number', required: false, description: '状态' },
        { name: 'page', type: 'number', required: true, description: '页码' },
        { name: 'pageSize', type: 'number', required: true, description: '每页数量' }
      ],
      pagination: true,
      cache: true,
      cacheTime: 300
    })
    
    ElMessage.success('接口生成成功')
    aiGenerating.value = false
    showAIDialog.value = false
    dialogVisible.value = true
    aiPrompt.value = ''
  }, 2000)
}
</script>

<style scoped>
.api-designer-page {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 10px;
  
  h2 {
    margin: 0;
    font-size: 24px;
    color: #303133;
  }
}

.header-actions {
  display: flex;
  gap: 10px;
}

.designer-layout {
  display: flex;
  gap: 20px;
  height: calc(100vh - 120px);
}

/* 左侧分类面板 */
.category-panel {
  width: 280px;
  flex-shrink: 0;
  
  .category-card {
    height: 100%;
    display: flex;
    flex-direction: column;
  }
  
  .category-content {
    flex: 1;
    overflow-y: auto;
  }
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.tree-node {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding-right: 10px;
  
  .node-label {
    display: flex;
    align-items: center;
    gap: 8px;
    flex: 1;
    
    .el-icon {
      color: #409eff;
    }
  }
  
  .count-badge {
    margin-left: 8px;
  }
  
  .node-actions {
    display: none;
    gap: 5px;
  }
  
  &:hover .node-actions {
    display: flex;
  }
}

/* 中间接口列表面板 */
.api-list-panel {
  width: 400px;
  flex-shrink: 0;
  
  .api-card {
    height: 100%;
    display: flex;
    flex-direction: column;
  }
}

.search-form {
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.api-list {
  flex: 1;
  overflow-y: auto;
}

.api-item {
  padding: 15px;
  margin-bottom: 10px;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover {
    border-color: #409eff;
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
  }
  
  &.active {
    border-color: #409eff;
    background: #f0f7ff;
  }
  
  .api-item-header {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 8px;
    
    .api-name {
      flex: 1;
      font-weight: bold;
      font-size: 14px;
      color: #303133;
    }
  }
  
  .api-path {
    font-size: 12px;
    color: #409eff;
    font-family: 'Courier New', monospace;
    margin-bottom: 8px;
  }
  
  .api-description {
    font-size: 12px;
    color: #909399;
    margin-bottom: 10px;
    line-height: 1.5;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }
  
  .api-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .api-time {
      font-size: 12px;
      color: #c0c4cc;
    }
    
    .api-actions {
      display: none;
      gap: 5px;
    }
  }
  
  &:hover .api-actions {
    display: flex;
  }
}

/* 编辑器区域 */
.api-editor {
  height: calc(100vh - 200px);
  overflow-y: auto;
}

.config-card,
.sql-card {
  height: 100%;
}

:deep(.el-card__header) {
  padding: 12px 20px;
}

:deep(.el-card__body) {
  height: calc(100% - 57px);
  overflow-y: auto;
}

.sql-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.sql-content {
  position: relative;
}

.params-config {
  margin-top: 10px;
}

.param-item {
  display: flex;
  gap: 10px;
  align-items: center;
  margin-top: 10px;
}

.form-tip {
  margin-left: 10px;
  color: #909399;
  font-size: 12px;
}

.tables-list {
  padding: 10px;
}

.table-fields {
  padding-left: 20px;
}

.field-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 5px 0;
  font-size: 13px;
}

.field-name {
  font-family: 'Courier New', monospace;
  font-weight: bold;
  min-width: 120px;
}

.field-type {
  color: #409eff;
  min-width: 100px;
}

.field-comment {
  color: #909399;
}

.sql-result {
  margin-top: 20px;
}

.result-info {
  display: flex;
  gap: 20px;
  margin-top: 10px;
  font-size: 12px;
  color: #909399;
}

.test-container {
  padding: 10px;
}

.test-param {
  margin-bottom: 10px;
}

.test-response {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.response-status {
  display: flex;
  justify-content: space-between;
  padding: 10px;
  background: #f56c6c;
  color: white;
}

.response-status.success {
  background: #67c23a;
}

.response-body {
  padding: 15px;
  margin: 0;
  background: #f5f5f5;
  font-family: 'Courier New', monospace;
  font-size: 13px;
  max-height: 400px;
  overflow-y: auto;
}

code {
  padding: 2px 6px;
  background: #f5f5f5;
  border-radius: 3px;
  font-family: 'Courier New', monospace;
  color: #e96900;
}
</style>

